#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma comment(lib, "ws2_32.lib")

#define PORT 8080
#define BUFFER_SIZE 1024

void handle_error(const char* message) {
    perror(message);
    exit(EXIT_FAILURE);
}

int main() {
    WSADATA wsaData;
    int server_socket, client_socket;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_len = sizeof(client_addr);

    // 1. 初始化 Winsock
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        handle_error("Failed to initialize Winsock");
    }

    // 2. 创建服务器套接字
    server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (server_socket == INVALID_SOCKET) {
        handle_error("Failed to create server socket");
    }

    // 3. 绑定地址和端口
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = INADDR_ANY;
    memset(&server_addr.sin_zero, 0, 8);

    if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
        handle_error("Failed to bind");
    }

    // 4. 监听连接请求
    if (listen(server_socket, SOMAXCONN) == SOCKET_ERROR) {
        handle_error("Failed to listen");
    }

    printf("Server is listening on port %d...\n", PORT);

    while (1) {
        // 5. 接受客户端连接
        client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_len);
        if (client_socket == INVALID_SOCKET) {
            handle_error("Failed to accept connection");
        } else {
            printf("Accepted connection from client: %s:%d\n",
                   inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

            char buffer[BUFFER_SIZE];
            int bytes_received;

            // 6. 读取客户端发送的数据
            while ((bytes_received = recv(client_socket, buffer, BUFFER_SIZE - 1, 0)) > 0) {
                buffer[bytes_received] = '\0';
                printf("Received from client: %s\n", buffer);

                // 7. 将数据回发给客户端
                send(client_socket, buffer, bytes_received, 0);
            }

            if (bytes_received == 0) {
                printf("Client disconnected.\n");
            } else {
                handle_error("Error receiving data");
            }

            // 关闭客户端套接字
            closesocket(client_socket);
        }
    }

    // 8. 关闭服务器套接字
    closesocket(server_socket);
    WSACleanup();

    return 0;
}